package com.game.database;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;

import com.mysql.jdbc.Statement;
import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;

/**
 * <strong>mysql数据库操作帮助类</strong>
 * <p>
 * 包装了mysql常用的操作方法。类似于SqlHelper在java中的实现。
 * </p>
 * 
 * @author birdshover
 */
public abstract class MysqlHelper {
    private static Boolean locker = false;
    
    private static DBConnection dbConn = new DBConnection();
    
    /**
     * 返回数据库连接对象，连接失败则返回null
     * 
     * @return Connection
     */
    private static Connection getConnection() {
        try {
        	return dbConn.getConnection();
        } catch (Exception ex) {
            return null;
        }
    }

    /**
     * 无结果查询，适用于更新和插入
     * 
     * @param SQL语句
     * @param 语句带的参数
     * @return 操作影响行数
     * @throws SQLException
     * 
     * @example Object[] parms = new Object[2];<br/> parms[0] = "标题"; <br/>
     *          parms[1] = "内容";<br/> int val = mysqlhelper.ExecuteNoneQuery(
     *          "insert into Documents(Title,Content) values (?,?)", parms);
     */
    public static int ExecuteNoneQuery(String cmdtext, Object[] parms)
            throws SQLException {
        PreparedStatement pstmt = null;
        Connection conn = null;
        try {
            conn = getConnection();
            pstmt = conn.prepareStatement(cmdtext);
            prepareCommand(pstmt, parms);
            return pstmt.executeUpdate();
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        } finally {
            if (pstmt != null){
                pstmt.clearParameters();
                pstmt.close();
            }
            dbConn.release(conn);
        }
        return 0;
    }
    /**
     * 插入 返回 insert id
     * 
     * @param SQL语句
     * @param 语句带的参数
     * @return 操作影响行数
     * @throws SQLException
     * 
     * @example Object[] parms = new Object[2];<br/> parms[0] = "标题"; <br/>
     *          parms[1] = "内容";<br/> int val = mysqlhelper.ExecuteInsert(
     *          "insert into Documents(Title,Content) values (?,?)", parms);
     */
    public static int ExecuteInsert(String cmdtext, Object[] parms)
            throws SQLException {
        PreparedStatement pstmt = null;
        Connection conn = null;
        try {
            conn = getConnection();
            pstmt = conn.prepareStatement(cmdtext,Statement.RETURN_GENERATED_KEYS);
            prepareCommand(pstmt, parms);
            pstmt.executeUpdate();
            ResultSet rs = pstmt.getGeneratedKeys();
            if(rs.next()){
            	return rs.getInt(1);
            }
            else
            	return 0;
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        } finally {
            if (pstmt != null){
                pstmt.clearParameters();
                pstmt.close();
            }
            dbConn.release(conn);
            
        }
        return 0;
    }
    /**
     * 返回查询结果集
     * 
     * @param SQL语句
     * @param 附带参数
     * @return 返回结果，用ArrayList包装Object数组
     * @throws SQLException
     * 
     * @example ArrayList list =
     *          mysqlhelper.ExecuteReader("Select * from Documents",null); <br/>
     *          for(int i = 0;i&lt;list.size();i++) { <br/> &nbsp;&nbsp;Object[]
     *          obs = (Object[])list.get(i); <br/> &nbsp;&nbsp;for(int j =
     *          0;j&lt;obs.length;j++) { <br/>
     *          &nbsp;&nbsp;&nbsp;&nbsp;out.print(obs[j].toString()); <br/>
     *          &nbsp;&nbsp;} <br/> &nbsp;&nbsp;out.print("&lt;br/&gt;"); <br/>
     *          } <br/>
     * 
     */
    public static ArrayList ExecuteReader(String cmdtext, Object[] parms)
            throws SQLException {
        PreparedStatement pstmt = null;
        Connection conn = null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            pstmt = conn.prepareStatement(cmdtext);

            prepareCommand(pstmt, parms);
            rs = pstmt.executeQuery();

            ArrayList al = new ArrayList();
            ResultSetMetaData rsmd = rs.getMetaData();
            int column = rsmd.getColumnCount();

            while (rs.next()) {
                Object[] ob = new Object[column];
                for (int i = 1; i <= column; i++) {
                    ob[i - 1] = rs.getObject(i);
                }
                al.add(ob);
            }
            return al;

        } catch (Exception ex) {
        }
        finally{
            if (rs != null)
                rs.close();
            if (pstmt != null)
                pstmt.close();
            dbConn.release(conn);
        }
        return null;
    }
    
    public static HashMap<String, Object> ExecuteRow(String cmdtext, Object[] params)
    throws SQLException
    {
    	 PreparedStatement pstmt = null;
         Connection conn = null;
         ResultSet rs = null;
         try {
             conn = getConnection();

             pstmt = conn.prepareStatement(cmdtext);
             prepareCommand(pstmt, params);

             rs = pstmt.executeQuery();
             ResultSetMetaData rsmd = rs.getMetaData();
             int column = rsmd.getColumnCount();
             if (rs.next()) {
            	 HashMap<String, Object> ob = new HashMap<String, Object>();
                 for (int i = 1; i <= column; i++) {
                     ob.put(rsmd.getColumnName(i), rs.getObject(i));
                 }
            	 return ob;
             } else {
                 return null;
             }
         } catch (Exception e) {
             System.out.println(e.getMessage());
         } finally {
             if (rs != null)
                 rs.close();
             if (pstmt != null)
                 pstmt.close();
             dbConn.release(conn);
         }
         return null;
    }

    /**
     * 返回第1行第1列数据，一般用来查询count值
     * 
     * @param SQL语句
     * @param 带参数
     * @return 值
     * @throws SQLException
     */
    public static Object ExecuteScalar(String cmdtext, Object[] parms)
            throws SQLException {
        PreparedStatement pstmt = null;
        Connection conn = null;
        ResultSet rs = null;
        try {
            conn = getConnection();

            pstmt = conn.prepareStatement(cmdtext);
            prepareCommand(pstmt, parms);

            rs = pstmt.executeQuery();
            if (rs.next()) {
                return rs.getObject(1);
            } else {
                return null;
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            if (rs != null)
                rs.close();
            if (pstmt != null)
                pstmt.close();
            dbConn.release(conn);
        }
        return null;
    }

    private static void prepareCommand(PreparedStatement pstmt, Object[] parms)
            throws SQLException, IOException {
        if (parms != null && parms.length > 0) {
            for (int i = 1; i < parms.length + 1; i++) {
                Object item = parms[i - 1];
                String typeName = item.getClass().getSimpleName();
                if (typeName.equals("String")) { 
                    pstmt.setString(i, item.toString());
                } else if (typeName.equals("Integer")) {
                    pstmt.setInt(i, Integer.parseInt(item.toString()));
                } else if (typeName.equals("Date")) {
                    pstmt.setDate(i, Date.valueOf(item.toString()));
                } else if (typeName.equals("byte[]")) {
                	InputStream is = new ByteInputStream((byte[])item,((byte[])item).length);
                	pstmt.setBinaryStream(i, is, is.available());
                } else {
                    pstmt.setObject(i, item);
                }
            }
        }
    }
}
